package com.itheima.reggie.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.util.DownloadUtil;
import com.itheima.reggie.util.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


/*
文件上传与下载
*/
@Slf4j//日志信息
@RestController//以json形式返回
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    //注意 : import的应该是springboot的value方法,不是lombok的方法
    private String basePath;

    /**
     * 文件上传
     */

   /* 通过MultipartFile类型的参数接收上传文件，形参要与页面的file域的name属性一致。
   public  R<String> upload(MultipartFile file) {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //分割原始文件名，得到.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t8BJH7LvDguSkrqiwW5";
        String accessKeySecret = "vOODny1kIOAL3Evgv2qMOALsigXXBU";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "reggie-waimai";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = fileName;
        //String filePath= "D:\\img";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
       try {
           //InputStream inputStream = new FileInputStream(filePath);
           // 创建PutObjectRequest对象。
           PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
           // 设置该属性可以返回response。如果不设置，则返回的response为空。
           putObjectRequest.setProcess("true");
           // 创建PutObject请求。
           PutObjectResult result = ossClient.putObject(putObjectRequest);
           // 如果上传成功，则返回200。
           System.out.println(result.getResponse().getStatusCode());
       } catch (OSSException oe) {
           System.out.println("Caught an OSSException, which means your request made it to OSS, "
                   + "but was rejected with an error response for some reason.");
           System.out.println("Error Message:" + oe.getErrorMessage());
           System.out.println("Error Code:" + oe.getErrorCode());
           System.out.println("Request ID:" + oe.getRequestId());
           System.out.println("Host ID:" + oe.getHostId());
       } catch (ClientException ce) {
           System.out.println("Caught an ClientException, which means the client encountered "
                   + "a serious internal problem while trying to communicate with OSS, "
                   + "such as not being able to access the network.");
           System.out.println("Error Message:" + ce.getMessage());
       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       } finally {
           if (ossClient != null) {
               ossClient.shutdown();
           }
       }
return R.success(fileName);


*/
        /*//此处的key一定要设置成file
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
       log.info(file.toString());
       //原始文件名
        // file.getOriginalFilename(): 得到上传时的文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        //分割原始文件名，得到.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }
        //将临时文件转存到指定位置
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  R.success(fileName);*/

    // return null;
    @PostMapping("/upload")
    public R<String> uoImg(MultipartFile file) throws IOException {

        return R.success(UploadUtil.uploadImage(file));
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        DownloadUtil.upDown(name, response);
    }
}

